package com.amos.isearch.common.parser;

import lombok.extern.slf4j.Slf4j;
import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.node.Link;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;

import java.util.Collections;
import java.util.List;

/**
 * DESCRIPTION: markdown parser
 *
 * @author <a href="mailto:daoyuan0626@gmail.com">amos.wang</a>
 * @date 2021/1/23
 */
@Slf4j
public class MarkdownParser {

    public static String parseHtml(String content) {
        // 文本内容转化为HTML
        List<Extension> extensions = Collections.singletonList(TablesExtension.create());

        Parser parser = Parser.builder().extensions(extensions).build();
        Node document = parser.parse(content);
        HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions)
                .attributeProviderFactory(context -> (node, s, map) -> {
                    // 改变a标签的target属性为_blank
                    if (node instanceof Link) {
                        map.put("target", "_blank");
                    }
                })
                .build();

        return renderer.render(document);
    }

}
